<script setup >
import { ref, onMounted, getCurrentInstance, inject, computed } from 'vue'
import { message } from 'ant-design-vue';

const emits = defineEmits(['change', 'expand', 'expandedRowsChange', 'resizeColumn'])
const attrs = ref({})

const rowSelection = inject('rowSelection', {})
const fieldNames = inject('fieldNames', { id: 'id', name: 'name' })
const tableData = inject('tableData', [])
const columns = inject('columns', [])
const changeSelectRows = inject('changeSelectRows', () => { })

onMounted(() => {
  const { ctx } = getCurrentInstance()
  attrs.value = ctx.$attrs
})

const tableObj = computed(() => {
  const obj = {
    ...attrs.value,
    rowSelection: rowSelection?.value ?? null,
    rowKey: fieldNames?.id || 'id',
    dataSource: tableData?.value || [],
    columns: columns,
    defaultExpandAllRows: true,
    rowClassName: (_record, index) => (index % 2 === 1 ? 'com-table-bm' : null),
    customRow: (row) => {
      if (!rowSelection?.value) {
        return
      }
      return {
        onClick: () => {
          if (!row.children) {
            changeSelectRows(row)
          } else {
            message.warning('只能选择子节点')
          }
        }
      }
    }
  }
  return obj
})

const change = function () {
  emits('change', arguments)
}
const expand = function () {
  emits('expand', arguments)
}
const expandedRowsChange = function () {
  emits('expandedRowsChange', arguments)
}
const resizeColumn = function () {
  emits('resizeColumn', arguments)
}
</script>

<template>
  <a-table v-bind="tableObj" @change="change" @expand="expand" @expandedRowsChange="expandedRowsChange"
    @resizeColumn="resizeColumn" :key="tableData?.[0]?.[fieldNames?.id] || '1'">
    <template #bodyCell="cellObj">
      <slot name="bodyCell" v-bind="cellObj" />
    </template>
  </a-table>
</template>